Back to course home
0% completed
Vote For New Content
Meta Hard Problems
Sliding Window Median (hard)
Solution: Sliding Window Median
Alien Dictionary (hard)
Solution: Alien Dictionary
Minimum Window Substring (hard)
Solution: Minimum Window Substring
Best Meeting Point (hard)
Solution: Best Meeting Point
Maximum Sum of 3 Non-Overlapping Subarrays (hard)
Solution: Maximum Sum of 3 Non-Overlapping Subarrays
Making A Large Island (hard)
Solution: Making A Large Island
Basic Calculator (Hard)
Solution: Basic Calculator
Serialize and Deserialize Binary Tree (hard)
Solution: Serialize and Deserialize Binary Tree
Longest Increasing Path in a Matrix (hard)
Solution: Longest Increasing Path in a Matrix
Valid Palindrome III (hard)
Solution: Valid Palindrome III
Shortest Path in Binary Matrix (medium)
Problem Statement
Given a matrix of size m x n, return the length of the shortest path from the top-left corner (0,0) to the bottom-right corner (N-1, N-1). If there is no such path, the output should be -1.
Follow the rules below while calculating the shortest path.
- You can move horizontally, vertically, and diagonally to adjacent cells.
- The visited cell should be
0. - The path length is counted as the number of steps taken.
Examples
- Example 1:
- Input:
[[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]
- Expected Output:
4 - Justification: The shortest path is (0, 0) -> (1, 0) -> (2, 1) -> (2, 2), totaling 4 steps.
- Example 2:
- Input:
[[0, 1, 0],
[0, 0, 0],
[0, 1, 0]]
- Expected Output:
3 - Justification: The shortest path is (0, 0) -> (1, 1) -> (2, 2), totaling 3 steps.
- Example 3:
- Input:
[1, 1, 1],
[0, 1, 1],
[0, 0, 0]]
- Expected Output:
-1 - Justification: The top-left cell can't be visited, as its value is 1. So, it returns -1.
Try it yourself
Try solving this question here:
Java
Saved to Cloud
. . . .
Solution: Diagonal Traverse
Solution: Shortest Path in Binary Matrix
Mark as Completed
On this page
Problem Statement
Examples
Try it yourself